<?php
/**
 * Created by a front-end programmer.
 * User: Xwen
 * Date: 2018/1/24
 * Time: 19:38
 * Mail:lauwencn@gmail.com
 */

class Controller extends SmartyView
{
    private $var = array();
    public function __construct()
    {
        if(C('SMARTY_ON')) parent::__construct();
        if(method_exists($this,'__init')){
            $this->__init();
        }
        if(method_exists($this,'__auto')){
            $this->__auto();
        }
    }

    /**
     * @param $var  需要传递的值的名称
     * @param $value    需要传递的值
     */
    protected function assign($var, $value){
        if(C('SMARTY_ON')){
            parent::assign($var, $value);
        }else{
            $this->var[$var] = $value;
        }
    }

    /**
     * 获取模板地址
     * @param $tpl
     * @return string
     */
    protected function get_tpl($tpl){
        if(is_null($tpl)){
            $path = APP_TPL_PATH.'/'.CONTROLLER.'/'.METHOD.'.html';
        }else{
            $suffix = strrchr($tpl,'.');
            $tpl = empty($suffix) ? $tpl.'.html' : $tpl;
            $path = APP_TPL_PATH.'/'.CONTROLLER.'/'.$tpl;
        }
        return $path;
    }
    /**
     * 模板载入函数
     * @param null $tpl 需要载入的模板名称(可带后缀)
     */
    protected function display($tpl=NULL){
        $path = $this->get_tpl($tpl);
        if(!is_file($path)) half($path.'模板文件不存在');
        if(C('SMARTY_ON')){
            parent::display($path);
        }else{
            extract($this->var);
            include $path;
        }
    }

    /**
     * @param $msg
     * @param null $jumpUrl
     * @param int $time
     * success方法，成功跳转页
     */
    protected function success($msg, $jumpUrl = NULL, $time = 3){
        $url = $jumpUrl ? "window.location.href='".$jumpUrl."'" : "window.history.back(-1)";
        include APP_TPL_PATH.'/success.html';
        die;
    }

    /**
     * @param $error
     * @param null $jumpUrl
     * @param int $time
     * error方法，失败跳转页
     */
    protected function error($error, $jumpUrl = NULL, $time = 3){
        $url = $jumpUrl ? "window.location.href='".$jumpUrl."'" : "window.history.back(-1)";
        include APP_TPL_PATH.'/error.html';
        die;
    }
}


?>